import React, { Component } from 'react';
import { withRouter, Route } from 'react-router-dom';
import { Icon, Tools, Bubble, ActivityIndicator, PhotoSwipe, Modal } from 'weaver-mobile';
import { RouteLayout } from 'weaver-mobile-page';

const { getWeaverFile, getLabel } = Tools;

function getType(name) {
  let type;
  let ext = '';
  name = name.toLowerCase();
  const i = name.lastIndexOf('.');
  if(i > -1){ ext = name.substring(i + 1); }
  switch(ext) {
    case 'doc': case 'docx': case 'wps': case 'txt': case 'md':
      type = 'word'; break;
    case 'rar': case 'zip': case 'gz': case 'z': case '7z':
      type = 'rar';   break;
    case 'xls': case 'xlsx':
      type = 'excel'; break; 
    case 'jpg': case 'png': case 'gif': case 'bmp': case 'jpeg':
      type = 'pic'; break; 
    case 'html': case 'htm': case 'xml': case 'jsp': case 'php': case 'js': case 'css':
      type = 'html'; break;
    case 'pdf':
      type = 'pdf'; break;
    case 'ppt': case 'pptx':
      type = 'combined-shape'; break;
    default:
      type = 'word'; break;
  }
  return type;
}

@withRouter
export default class FilePreview extends Component {
  static defaultProps = {
    prefixCls: "file-preview",
    file: { filename: '' },
  }
  
  constructor(props) {
    super(props);
    const { id, fileid, isCanPreviewForMobilespan, isCanPreviewForMobile, isImgspan, isImg, downloadUrlspan, previewUrl, filelink } = this.props.file;
    this.state = {
      id: id === undefined ? fileid : id,
      isImg: (isImgspan === undefined ? isImg : isImgspan) === 'true',
      isCanPreviewForMobile: (isCanPreviewForMobilespan === undefined ? isCanPreviewForMobile : isCanPreviewForMobilespan) === 'true',
      downloadUrl: downloadUrlspan === undefined ? filelink : downloadUrlspan,
      previewUrl: downloadUrlspan === undefined ? previewUrl : downloadUrlspan,
      filePreviewUrl: '',
      isPreviewable: 0,
      message: '',
      loading: true,
    };
  }

  componentDidMount() {
    const isiPhone = Tools.mobileDetect().is('iPhone');
    const isEmobile = Tools.mobileDetect().isEmobile();
    const { history } = this.props;
    const { id, isImg, isCanPreviewForMobile, downloadUrl, previewUrl } = this.state;
    let filePreviewUrl = '';
    if (isImg) {
      filePreviewUrl = previewUrl;
      this.setState({ loading: false, filePreviewUrl, isPreviewable: 1 });
    } else if (isCanPreviewForMobile) {
      // Api.convertFile({ id }).then(res => {
      //   const { result, data, message } = res;
      //   if (!result) {
      //     filePreviewUrl = Array.isArray(data) && data.length > 0 ? data[0].path : '';
      //     this.setState({ loading: false, filePreviewUrl, isPreviewable: 1 });
      //   } else {
      //     Bubble.error(message, 2, {top: '50%'});
      //     history.go(-1);
      //   }
      // });
    } else {
      this.curentModal = Modal.alert(getLabel('514232','当前文件不可预览') , getLabel('514233','是否下载？'), [
        { text: getLabel('31129', '取消'), onPress: () => { history.go(-1) } },
        { text: getLabel('826', '确定'), onPress: () => {
          if (isiPhone&&!isEmobile) {
            window.open(downloadUrl + "&_ec_ismobile=true");
          } else {
            getWeaverFile(downloadUrl + "&_ec_ismobile=true", 'iframe');
            history.go(-1);
          }
        }},
      ])
    }
  }

  componentWillUnmount() {
    typeof this.curentModal === 'function' && this.curentModal.close()
  }

  renderIcon = (name) => {
    const { prefixCls } = this.props;
    const icon = getType(name);
    return (<Icon className={`${prefixCls}-filetype icon-${icon}`} type={icon} />);
  }

  render() {
    const { prefixCls, path } = this.props;
    const { loading, filePreviewUrl, isPreviewable, isImg, isCanPreviewForMobile } = this.state;
    if (loading) {
      return (
        <Route
          key="filePreview"
          path={path}
          render={() => (
            <RouteLayout>
              <div key="filePreview" className={`${prefixCls} wm-route-layout`}>
                <div className={`${prefixCls}-loading`}><ActivityIndicator size="large" text="loading..." /></div>
              </div>
            </RouteLayout>
          )}
        />
      );
    } else if (isPreviewable) {
      if (isImg) {
        return (<Route
          key="filePreview"
          path={path}
          render={() => (
            <RouteLayout>
              <div key="filePreview" className={`${prefixCls} wm-route-layout`}>
                <img src={filePreviewUrl} alt="" onClick={() => PhotoSwipe.showImage([{url: filePreviewUrl}], 0)}/>
              </div>
            </RouteLayout>
          )}
        />);
      } else if (isCanPreviewForMobile) {
        return (<RouteLayout.Frame id="preview-frame" path={path} iframeProps={{ src: filePreviewUrl }} />);
      }
    }
    return null;
  }
}
